/**
 * @author daemach
 */

colorWeasel = function(){
	this.name = "colorWeasel"
	this.version = "1.0"
}
jQuery.extend(colorWeasel,{
	prototype:{
		rgb2hsl: function(rgb){
			rgb = this.rgb2hex(rgb)
			r = parseInt(rgb.substr(0,2),16)/255;	
			g = parseInt(rgb.substr(2,2),16)/255;
			b = parseInt(rgb.substr(4,2),16)/255;
			var max = Math.max(r, g, b),
				min = Math.min(r, g, b),
				delta = (max-min),
				l = (max + min) / 2,
				h = 0,
				s = 0,
				dR,dG,dB;
		    if(max != min){
		        s = (l < .5)? (max - min) / (max + min) : (max - min) / (2 - max - min);		
				dR = (((max-r)/6) + (delta/2)) / delta;
				dG = (((max-g)/6) + (delta/2)) / delta;
				dB = (((max-b)/6) + (delta/2)) / delta;
				h = (max != r) ? (max != g) ? ((2/3) + dG - dR) : ((1/3) + dR - dB) : (dB - dG);	
		    }
		    if (h < 0) { h += 1; };
			if (h > 1) { h -= 1; };	       
			h *= 360;
		    return [h, s, l];
		},
		hsl2rgb: function(h, s, l){ // H as degrees 0..360, S L as decimals, 0..1.
			if (typeof h == "object" && h.constructor == Array){
				l=h[2]; 
				s=h[1]; 
				h=h[0];
			}
		    h /= 360;
		    var y = (l > .5)? (l + s) - (l * s) : l * (s + 1),
		    x = l * 2 - y,
		    r = Math.round(255 * _hue2Rgb(x, y, h + (1 / 3))),
		    g = Math.round(255 * _hue2Rgb(x, y, h)),
		    b = Math.round(255 * _hue2Rgb(x, y, h - (1 / 3)));
				
		    function _hue2Rgb(x, y, h){
		        if(h < 0){
		            h += 1;
				} else if (h > 1){
		            h -= 1;			
				}

		        return ((h * 6) < 1) ? (x +(y - x) * h * 6) : ((h * 2) < 1) ? y : ((h * 3) < 2) ? (x + (y - x) * ((2 / 3) - h) * 6) : x;
		    }
		    return zeroPad(r.toString(16)).toUpperCase()+zeroPad(g.toString(16)).toUpperCase()+zeroPad(b.toString(16)).toUpperCase();
		},
		zeroPad: function(num) {
			var str = '0'+num;
			return str.substring(str.length-2);
		},
		rgb2hex: function(rgb){
			if (!rgb.match(/(rgb\()[^\)]+(\))/)){
				return rgb;
			} 
			var t = /(rgb\()([^\)]+)(\))/.exec(rgb);
			t = t[2].replace(/\s+/g,"").split(",");
			var r = parseInt(t[0]).toString(16).toUpperCase();
			var g = parseInt(t[1]).toString(16).toUpperCase();
			var b = parseInt(t[2]).toString(16).toUpperCase();	
		
			return r + g + b;
		},
		ccLighter: function (rgb,perc){
			var hsl = rgb2hsl(rgb);
			hsl[2] += (hsl[2] *= perc);
			hsl[2] = (hsl[2] >= 1) ? 1 : hsl[2];
			rgb = hsl2rgb(hsl);
			return rgb;
		},
		ccDarker: function (rgb,perc){
			var hsl = rgb2hsl(rgb);
			hsl[2] -= (hsl[2] *= perc);
			hsl[2] = (hsl[2] <= 0) ? 0 : hsl[2];
			rgb = hsl2rgb(hsl);
			return rgb;
		},
		ccComplementary: function (rgb){
			var hsl = rgb2hsl(rgb);
			hsl[0] += 180;
			hsl[0] = (hsl[0] > 360) ? hsl[0]-360 : hsl[0];
			rgb = hsl2rgb(hsl);
			return rgb;
		}
	}
});

var colorWeasel = new colorWeasel();

